/*
 * Copyright 2014 Walter Lütgenau.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package offset.nodes.client.veditor.model;

import java.util.LinkedList;
import java.util.List;
import javax.swing.text.Element;

/**
 *
 * @author Walter Lütgenau
 */
public class BrowserElementActionModel {
    public static final String ATTRIBUTE_NAME_ELEMENT_ACTION = "n-action";
    DataModel model;

    public BrowserElementActionModel(DataModel model) {
        this.model = model;
    }
    
    /**
     * Add a named action to the element.
     * 
     * @param e the element
     * @param actionName the action name
     */
    public void add(Element e, String actionName) {
        if (actionName == null || actionName.length() == 0)
            model.removeAttribute(e, ATTRIBUTE_NAME_ELEMENT_ACTION);
        else
            model.addAttribute(e, ATTRIBUTE_NAME_ELEMENT_ACTION, actionName);
    }
    
   /**
     * Return the name of the element action
     * 
     * @param e the element
     * @return the name or null, if no element action is associated to the element
     */
    public String getElementActionName(Element e) {
        if (!e.getAttributes().isDefined(ATTRIBUTE_NAME_ELEMENT_ACTION))
            return null;
        return (String) e.getAttributes().getAttribute(ATTRIBUTE_NAME_ELEMENT_ACTION);
    }

    /**
     * Return the values of the n-action attributes in the
     * document.
     *
     * @return the element actions
     */
    public String[] saveElementActions() {
        List<String> queries = new LinkedList<String>();
        Element root = model.getContext().getDocument().getRootElements()[0];
        addElementActions(root, queries);

        return queries.toArray(new String[queries.size()]);
    }

    /**
     * Add the values of the query attribute associated
     * to the element and its children
     * 
     * @param e
     * @param queries
     */
    public void addElementActions(Element e, List<String> queries) {
        String query = getElementActionName(e);
        if (query != null)
            queries.add(query);

        for (int i = 0; i < e.getElementCount(); i++)
            addElementActions(e.getElement(i), queries);
    }

    
}
